#include "widget.h"
#include "ui_widget.h"
#include <QNetworkDatagram>
#include <QMessageBox>
#include <QNetworkReply>


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    networkAccessManager = new QNetworkAccessManager(this);
}

void Widget::on_pushButton_clicked()
{
    QUrl url(ui->lineEdit->text());
    //构建http请求
    QNetworkRequest request(url);
    //发送get请求
    QNetworkReply* response = networkAccessManager->get(request);
    connect(response,&QNetworkReply::finished,[=](){
       if(response->error() == QNetworkReply::NoError)
       {
           QString html = response->readAll();
           ui->plainTextEdit->setPlainText(html);
       }
       else
       {
           ui->plainTextEdit->setPlainText(response->errorString());
       }
       response->deleteLater();
    });

}

//const QString server_ip = "127.0.0.1";
//const quint16 server_port = 9999;

//Widget::Widget(QWidget *parent)
//    : QWidget(parent)
//    , ui(new Ui::Widget)
//{
//    ui->setupUi(this);
//    this->setWindowTitle("客户端");

//    tcpSocket = new QTcpSocket(this);
//    //与服务器建立连接
//    tcpSocket->connectToHost(server_ip,server_port);
//    //等待并确认连接是否出错
//    if(!tcpSocket->waitForConnected())
//    {
//        QMessageBox::critical(nullptr, "连接服务器出错!", tcpSocket->errorString());
//        exit(1);
//    }

//    connect(tcpSocket,&QTcpSocket::readyRead,[=](){
//        QString response = tcpSocket->readAll();
//        qDebug() << response;
//        ui->listWidget->addItem(QString("服务器说: ") + response);
//    });
//}

//void Widget::on_pushButton_clicked()
//{
//    //1.获取到输入框中的内容
//    QString inputText = ui->lineEdit->text();
//    ui->listWidget->addItem("客户端说:" + inputText);
//    ui->lineEdit->setText("");
//    //2.发送
//    tcpSocket->write(inputText.toUtf8());
//}

Widget::~Widget()
{
    delete ui;
}



//const QString server_ip = "127.0.0.1";
//const quint16 server_port = 9999;

//Widget::Widget(QWidget *parent)
//    : QWidget(parent)
//    , ui(new Ui::Widget)
//{
//    ui->setupUi(this);
//    this->setWindowTitle("客户端");

//    udpSocket = new QUdpSocket(this);
//    //这里一定是先创建udpSocket,否则connect会访问udpSocket,此时它还是nullptr,运行崩溃
//    connect(udpSocket,&QUdpSocket::readyRead,this,&Widget::receiveResponse);
//}

//Widget::~Widget()
//{
//    delete ui;
//}

//void Widget::receiveResponse()
//{
//    const QNetworkDatagram responseDatagram = udpSocket->receiveDatagram();
//    const QString response = responseDatagram.data();
//    ui->listWidget->addItem("服务器响应：" + response);
//}

//void Widget::on_pushButton_clicked()
//{
//    //1.获取到输入框中的内容
//    QString inputText = ui->lineEdit->text();
//    //2.构建请求
//    QNetworkDatagram requestDatagram(inputText.toUtf8(),QHostAddress(server_ip),server_port);
//    //3.发送请求
//    udpSocket->writeDatagram(requestDatagram);

//    ui->listWidget->addItem("客户端说:" + inputText);
//    ui->lineEdit->setText("");
//}


